﻿using BLL.Interface;
using Common;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Configuration;
using Model;
using Model.Enum;
using System.Drawing;
using System.Text.RegularExpressions;

namespace BLL
{
    /// <summary>
    /// 验证码业务逻辑层
    /// </summary>
    public class CaptchaBLL : ICaptchaBLL
    {
        private readonly IMemoryCache _memoryCache;
        private readonly IConfiguration _configuration;
        public CaptchaBLL(
            IMemoryCache memoryCache,
            IConfiguration configuration
            )
        {
            _memoryCache = memoryCache;
            _configuration = configuration;
        }
        /// <summary>
        /// 获取图片验证码
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="expiredTime"></param>
        /// <returns></returns>
        public async Task<byte[]> GetImageCaptcha(string appId,DateTime expiredTime)
        {
            try
            {
                var result = CaptchaHelper.GenerateCaptcha();
                await Task.Run(() => _memoryCache.Set(appId, result.Item2.ToLowerInvariant(), expiredTime));
                var bytes = CaptchaHelper.BitmapToByte(result.Item1);
                return bytes;
            }
            catch
            {
                return Array.Empty<byte>();
            }
        }
        /// <summary>
        /// 获取邮箱验证码
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public async Task<ResponseMessage> GetEmailCaptcha(string email,DateTime expiredTime)
        {
            try
            {
                string verifyCode = EmailHelper.GenerateCode();
                if (!Regex.IsMatch(email, @"^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+$"))
                {
                    return ResponseMessage.CreateError("邮箱格式不正确");
                }
                var sendEmailDTO = new SendEmailDTO()
                {
                    MailFrom = _configuration.GetValue<string>("EmailConfig:MailFrom"),
                    MailTo = email,
                    Title = "天下会论坛注册验证码",
                    Content = $"您的验证码为:{verifyCode}，请在{(expiredTime - DateTime.Now).TotalMinutes}分钟内完成验证",
                    MailFromAccount = _configuration.GetValue<string>("EmailConfig:MailFromAccount"),
                    MailFromPassword = _configuration.GetValue<string>("EmailConfig:MailFromPassword"),
                    ServerType = EmailServerType.SERVER_QQ_COM
                };
                var result = await Task.Run(() => EmailHelper.SendEmail(sendEmailDTO));
                if (result.Code == ResponseType.Success)
                {
                    verifyCode = verifyCode.ToLowerInvariant();
                    _memoryCache.Set(email, verifyCode, expiredTime);
                }
                return result;
            }
            catch
            {
                return ResponseMessage.CreateError("获取失败");
            }
        }
    }
}
